import Taro, { Component } from "@tarojs/taro";
import { connect } from "@tarojs/redux";
import { View, Text } from "@tarojs/components";
import { AtButton, AtInputNumber, AtSwipeAction, AtToast } from "taro-ui";
import NP from 'number-precision';
import { $Req } from "@utils";
import "./index.scss";
import "@components/ShowBox.scss";

const img_selected = "https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" + "/shopping/user/selected.png";
const img_select = "https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" + "/shopping/user/select.png";


@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "购物车",
  };

  constructor() {
    super(...arguments);
    this.state = {
      list: [],
      selectAll: false,
      totalMoney: "0.00",
      totalProduct: 0,
      hintFlag: false,
      hintTxt: '',
    };
  }

  componentDidShow() {
    this.getGoodsCart();
    this.setState({
      selectAll: false,
      totalMoney: "0.00",
      totalProduct: 0
    })
  }

  async getGoodsCart() {
    const {
      userModel: { userInfo },
    } = this.props;
    let { data } = await $Req({
      type: "get",
      url: "/order/getCart",
      data: {
        userId: userInfo.userId
      },
    });
    if (!data) return;

    data.forEach((item) => {
      item.selected = false;
    });

    this.setState({
      list: data,
    });
  }
  isAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function(value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
  }
  onSubmit() {
    let orderArr = [];
    let shopVip = [];
    let { list, totalMoney, totalProduct} = this.state;

    list.forEach(el => {
      if (el.selected) {
        delete el.skuDetail;
        orderArr.push(el);
        shopVip.push(el.vip);
      }
    })

    if(!orderArr.length) {
      Taro.showToast({
        title: "请选择商品在进行结算",
        icon: "none"
      })
      return false;
    }
    if( orderArr.length > 1&& !this.isAllEqual(shopVip) ) {
      this.setState({
        hintFlag: true,
        hintTxt: '普通商品不能与会员商品一起结算' 
      })
      return false;
    }

    console.log(orderArr);

    // 结算
    Taro.navigateTo({
      url: `/pages/order/confirm/index?orderList=${ JSON.stringify(orderArr)}&totalMoney=${totalMoney}&totalProduct=${totalProduct}&source=cart`,
    });
  }

  async addProductNum(val, item, index, type) {
    let { list, totalMoney, totalProduct } = this.state;

    list[index].quantity = val;

    if (list[index].selected) {
      if (type == "plus") {
        totalMoney = NP.plus(totalMoney, NP.times(1,list[index].skuCurrPrice));
        totalProduct = NP.plus(totalProduct, 1);
      } else {
        totalMoney = NP.minus(totalMoney, NP.times(1,list[index].skuCurrPrice));
        totalProduct = NP.minus(totalProduct, 1);
      }
      
    }

    this.setState({
      list,
      totalMoney,
      totalProduct
    })

    const {
      userModel: { userInfo },
    } = this.props;

    let { code } = await $Req({
      type: "post",
      url: "/order/addCartSkuNum",
      data: {
        userId: userInfo.userId,
        quantity: val,
        cartId: item.cartId,
        skuId: item.skuId
      },
    });
    if (code != 200) return;
    
  }

  async delCart(cartId) {
    let { code } = await $Req({
      type: "get",
      url: "/order/delCart",
      data: {
        cartId,
      },
    });
    if (code != 200) return;
    
    Taro.showToast({
      title: "删除成功!"
    })

    this.getGoodsCart();
  }

  gotoDetails(skuId) {
    Taro.navigateTo({
      url: "/pages/mall/detail/index?goodsId=" + skuId,
    });
  }
  selectShopHandle(item,index,e) {

      e.stopPropagation();

console.log("===")
      let { list, totalMoney, totalProduct } = this.state;
      let listArr = list;
      listArr[index].selected = !item.selected;
      // 全选
      let all = list.every(el => el.selected == true);

      if (all != true) {
        this.setState({
          selectAll: false
        })
        
      } else {
        this.setState({
          selectAll: true,
        })
      }

      let totalM = 0, totalP = 0;
      list.map((i) => {
        if( i.selected ) {
          totalM = NP.plus(totalM, NP.times(i.quantity,i.skuCurrPrice));  
          totalP = NP.plus(totalP,1);   
        } 
      })
      
      this.setState({
        list:listArr,
        totalProduct:totalP,
        totalMoney: totalM == 0 ? "0.00" : totalM
      })
  }
  render() {
    const {hintFlag ,hintTxt} = this.state;
    return (
      <View className="page-cart-index">
        <View className="at-row">
          <View className="at-col c0">
            {this.state.list.map((item, index) => {
              return (
                <AtSwipeAction onClick={() => this.delCart(item.cartId)} key={item.cartId} options={[
                  {
                    text: '删除',
                    style: {
                      backgroundColor: '#FF4949'
                    }
                  }
                ]}>
                <View className="at-row shopping-show-box">
                  <View className="at-col show-box-c0">
                    <View className="at-row show-box-row">
                      <View className="at-col at-col-1 show-box-col-select" onClick={this.selectShopHandle.bind(this,item,index)}>
                        <image
                          className="img-select"
                          mode={"aspectFill"}
                          src={item.selected ? img_selected : img_select}
                        />
                      </View>
                      <View className="at-col at-col-3 show-box-col-img" 
                        onClick={(e) => {
                          this.gotoDetails(item.skuId);
                        }}
                      >
                        <image className="img-goods" mode={"aspectFill"} src={item.skuCoversUrl} />
                      </View>
                      <View className="at-col at-col-8 show-box-col-main" style={{ marginLeft: "10PX" }}>
                        <View className="at-row" 
                          onClick={(e) => {
                            this.gotoDetails(item.skuId);
                          }}
                        >
                          <View className="at-col">
                            <Text className="show-box-title">
                              {item.goodsName}
                            </Text>
                          </View>
                        </View>
                        <View className="goods-norms">
                          <View className="at-col"
                            onClick={(e) => {
                              this.gotoDetails(item.skuId);
                            }}
                          >
                            {/* {item.skuTitleType}: */}
                            <Text style={{padding: "2px 4px", backgroundColor: "#F1F1F1", borderRadius: "10px", fontSize:"12px"}} className="show-box-norms"> {item.skuTitle}</Text>
                          </View>
                          {
                            item.integralStatus ? 
                              <View className="at-col">
                                {/* {item.skuTitleType}: */}
                                <Text style={{padding: "2px 4px", fontSize:"12px"}} className="show-box-norms">积分商品</Text>
                              </View>
                            :
                             null
                          }
                          
                          <View className="at-row" style={{marginTop: "10PX"}}>
                            {/* <View className="at-col at-col-4"></View> */}
                            <View className="at-col at-col-4" 
                              onClick={(e) => {
                                this.gotoDetails(item.skuId);
                              }}
                            >
                              <Text className="show-box-price-large">
                                ￥{item.skuCurrPrice}
                              </Text>
                            <Text className="show-box-price-small">{item.skuCurrPrice >= 1 ? ".0元" : '元'}{item.vip*1==1?'':'/积分'}</Text>
                            </View>
                            <View
                              className="at-col at-col-7"
                              style="text-align:right;"
                            >
                              <AtInputNumber
                                disabledInput
                                min={1}
                                max={100}
                                step={1}
                                value={item.quantity}
                                onChange={(val, { currentTarget: { dataset: { eTapAA } } }) => { 
                                  this.addProductNum(val, item, index, eTapAA);
                                }}
                              />
                            </View>
                          </View>
                        </View>
                      </View>
                    </View>

                  </View>
                </View>
                </AtSwipeAction>
              );
            })}
          </View>
        </View>
        <View className="at-row bottom-row">
          <View className="at-col at-col-all">
            <View className="at-row at-row__justify--between at-row__align--center">
              <View className="at-col at-col-2" onClick={
                () => {
                  let { selectAll, list, totalProduct, totalMoney } = this.state;
                  totalProduct = 0;
                  totalMoney = 0;

                  if(!selectAll) {
                    list.forEach(el => {
                      el.selected = true;

                      if (el.selected) {
                        totalMoney += (el.quantity * el.skuCurrPrice);
                        totalProduct += 1
                      }

                    })
                  } else {
                    list.forEach(el => {
                      el.selected = false;
                    })

                    totalProduct = 0;
                    totalMoney = 0;
                  }
                  
                  this.setState({
                    totalProduct: totalProduct == 0 ? 0 : totalProduct,
                    totalMoney,
                    list,
                    selectAll: !selectAll
                  })
                }
              }>
                <image mode={"aspectFill"} src={this.state.selectAll ? img_selected : img_select} />
                <Text style="color:#999;font-size:12px;margin-left:5PX">
                  全选
                </Text>
              </View>
              <View className="at-col at-col-7">
                <Text style="color:#999;font-size:12PX;margin-right:15PX">
                  共{this.state.totalProduct}件商品
                </Text>
                <Text style="color:#1A1A1A;font-size:14PX;">合计:</Text>
               <Text style="color:#1A1A1A;font-size:16PX;">￥{this.state.totalMoney}</Text>
              </View>
              <View className="at-col at-col-3">
                <AtButton
                  circle
                  type="primary"
                  className="btn-submit"
                  onClick={() => {
                    this.onSubmit();
                  }}
                >
                  结算
                </AtButton>
              </View>
            </View>
          </View>
        </View>
        <AtToast isOpened={hintFlag} onClose={()=>{this.setState({hintFlag:false})}} text={hintTxt} hasMask={true}></AtToast>
      </View>
    );
  }
}
